import EventEmitter from "events";
import {OnSendHeadersListenerDetails, session} from "electron";
import {SessionName} from "../type/const.js";
import Session = Electron.Main.Session;
import {electronLogger} from "../vendor/electron-logger.js";

export class SearchSession extends EventEmitter {

  sessionName: string
  session: Session
  constructor() {
    super();
    this.sessionName = SessionName.Player
  }

  init(noCacheFunc: (a: string) => boolean){
    this.session = session.fromPartition(this.sessionName);
    this.watchRequest(noCacheFunc)
  }


  watchRequest(noCacheFunc: (a: string) => boolean) {
    this.session.webRequest.onSendHeaders((details: OnSendHeadersListenerDetails)=>{
      const { url, requestHeaders } = details;
      this.emit("source", { url, sessionName: this.sessionName, headers:requestHeaders})
    });

    this.session.webRequest.onHeadersReceived((details, callback) => {
      if (!details.responseHeaders) return
      if (noCacheFunc(details.url)) {
        if (details.responseHeaders['Cache-Control']) {
          details.responseHeaders['Cache-Control'] = ['no-cache, no-store, must-revalidate'];
        }
        if (details.responseHeaders['Pragma']) {
          details.responseHeaders['Pragma'] = ['no-cache'];
        }
      }
      callback({ responseHeaders: details.responseHeaders });
    });

  }
  private enableProxy(proxy: string) {
    if (!proxy) {
      return;
    }

    // Process the validity of the proxy address
    if (!/https?:\/\//.test(proxy)) {
      proxy = `http://${proxy}`;
    }

    this.session.setProxy({ proxyRules: proxy });
    electronLogger.info(`[Proxy] enable proxy: ${proxy}`);
  }

  private disableProxy() {
    this.session.setProxy({ proxyRules: "" });
    electronLogger.info(`[Proxy] disable proxy`);
  }

  setProxy(useProxy: boolean, proxyUrl: string): void {
    if (useProxy) {
      this.enableProxy(proxyUrl);
    } else {
      this.disableProxy();
    }
  }

}

export const searchSession = new SearchSession()
